package com.spsy.pay.config;

import com.spsy.pay.constant.RabbitmqConstantCompany;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMqConfigCompany {

    @Bean
    public Queue createQueue() {
     return new Queue(RabbitmqConstantCompany.RabbitMqConstantCompany.MQ_NAME, true);
 }

    @Bean
    public DirectExchange createExchange() {
        return new DirectExchange(RabbitmqConstantCompany.RabbitMqConstantCompany.MQ_EXCHANGE);
    }

    @Bean
    public Binding bindingCompany() {
        return BindingBuilder.bind(createQueue()).to(createExchange()).with(RabbitmqConstantCompany.RabbitMqConstantCompany.MQ_ROUTTING);
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);

        rabbitTemplate.setMandatory(true);

        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                System.out.println("消息发送成功=" + correlationData.getId());
            } else {
                System.out.println("消息发送失败，原因:" + cause + ",消息ID=" + correlationData.getId());
            }

        });

        rabbitTemplate.setReturnsCallback(returned -> {
            System.out.println("错误码- ReplyCode=" + returned.getReplyCode());
            System.out.println("错误原因- replyText=" + returned.getReplyText());
            System.out.println("交换机- exchange=" + returned.getExchange());
            System.out.println("routingKey=" + returned.getRoutingKey());
            System.out.println("消息-=" + new String(returned.getMessage().getBody()));
        });
        return rabbitTemplate;
    }


}
